package com.hanhai.material.wages.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.code.kaptcha.Producer;
import com.hanhai.material.common.constant.Constant;
import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultCode;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.model.user.UserModel;
import com.hanhai.material.utils.redis.RedisUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.beans.factory.annotation.Autowired;
import com.hanhai.material.wages.entity.SysUser;
import com.hanhai.material.wages.service.SysUserService;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.UUID;

import static com.hanhai.material.wages.entity.table.SysUserTableDef.SYS_USER;

/**
 *  控制层。
 *
 * @author youchuang
 * @since 2023/10/25 17:34:51
 */
@RestController
@RequestMapping("/user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    Producer producer;
    @Autowired
    RedisUtil redisUtil;



    @GetMapping("/captcha")
    public Result<?> getCaptcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        /*通过UUID生成随机key，并通过Kaptcha生成验证码图片*/
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        String str = "data:image/jpeg;base64,";
        String base64Img = str + Base64Encoder.encode(outputStream.toByteArray());
        /*将验证码的key保存到Redis*/
        redisUtil.hset(Constant.CAPTCHA_KEY, key, code, 60 * 3);
        return ResultTool.success(MapUtil.builder().put("token", key).put("captchaImg", base64Img).build());
    }
    /**
     * 添加。
     *
     * @param sysUser 
     * @return {@code true} 添加成功，{@code false} 添加失败
     */
    @PostMapping("save")
    public boolean save(@RequestBody SysUser sysUser) {
        return sysUserService.save(sysUser);
    }

    /**
     * 根据主键删除。
     *
     * @param id 主键
     * @return {@code true} 删除成功，{@code false} 删除失败
     */
    @DeleteMapping("remove/{id}")
    public boolean remove(@PathVariable Serializable id) {
        return sysUserService.removeById(id);
    }

    /**
     * 根据主键更新。
     *
     * @param sysUser 
     * @return {@code true} 更新成功，{@code false} 更新失败
     */
    @PutMapping("update")
    public boolean update(@RequestBody SysUser sysUser) {
        return sysUserService.updateById(sysUser);
    }

    /**
     * 查询所有。
     *
     * @return 所有数据
     */
    @GetMapping("list")
    public List<SysUser> list() {
        return sysUserService.list();
    }

    /**
     * 根据主键获取详细信息。
     *
     * @param id 主键
     * @return 详情
     */
    @GetMapping("getInfo/{id}")
    public SysUser getInfo(@PathVariable Serializable id) {
        return sysUserService.getById(id);
    }

    /**
     * 分页查询。
     *
     * @param page 分页对象
     * @return 分页对象
     */
    @GetMapping("page")
    public Page<SysUser> page(Page<SysUser> page) {
        return sysUserService.page(page);
    }


    @PostMapping("/login")
    public Result<?> login(@RequestBody SysUser sysUser){

        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_USER.USERNAME.eq(sysUser.getUsername()));
        SysUser user=this.sysUserService.getOne(queryWrapper);
        if(user==null){
            return ResultTool.fail(ResultCode.USER_ACCOUNT_NOT_EXIST);
        }else{
            boolean result=bCryptPasswordEncoder.matches(sysUser.getPassword(),user.getPassword());
            if(result){
                UserModel userModel= JSONObject.parseObject(JSONObject.toJSONString(user), UserModel.class);
                return ResultTool.success(userModel);
            }else{
                return ResultTool.fail(ResultCode.USER_CREDENTIALS_ERROR);
            }
        }
    }

}
